import 'package:flutter/material.dart';
import 'package:pin_input_text_field/pin_input_text_field.dart';
import 'package:ytbusiness/config/yt_theme.dart';
import 'package:ytbusiness/utils/helper.dart';
import 'package:ytbusiness/utils/screen_adaptation.dart';
import 'dart:async';

import 'package:ytbusiness/widgets/widgets.dart';

class ModifyMobilePhoneNumber extends StatefulWidget {
  @override
  _ModifyMobilePhoneNumberState createState() =>
      _ModifyMobilePhoneNumberState();
}

class _ModifyMobilePhoneNumberState extends State<ModifyMobilePhoneNumber>
    with SingleTickerProviderStateMixin {
  bool isDetectionEnvironment = false; //显示隐藏检测环境
  bool acquireOrFillIn  = false; //获取、填写验证码
  TabController _tabController; //tab控制器
  Timer _countdownTimer;//倒计时
  int _countdownNum = 60;//倒计时60s
  Timer timer; //定时器
  TextEditingController _phone = TextEditingController(); //手机号
  TextEditingController _checkCode = TextEditingController(); //验证码
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = new TabController(length: 2, vsync: this);
    timer = Timer.periodic(new Duration(milliseconds: 1), (val) {
      if (val.tick == 1000) {
        setState(() {
          isDetectionEnvironment = true;
        });
      }
      if (val.tick >= 1500) {
        setState(() {
          _tabController.animateTo(1);
        });
        timer.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        print('隐藏键盘⌨️,隐藏键盘⌨️,');
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
        appBar: customAppBar(context, title: "修改手机号"),
        body: TabBarView(
            controller: _tabController,
            physics: NeverScrollableScrollPhysics(),
            children: [
              //检测环境
              Container(
                color: Colors.white,
                child: ListView(
                  children: [
                    // 检测环境
                    Offstage(
                      offstage: isDetectionEnvironment,
                      child: Column(
                        children: [
                          SizedBox(
                            height: setWidth(70),
                          ),
                          Image.asset(
                            'assets/images/safetyInspection.gif',
                            width: setWidth(110),
                            height: setWidth(110),
                            fit: BoxFit.fill,
                          ),
                          SizedBox(
                            height: setWidth(30),
                          ),
                          Text(
                            '正在检测您的账户环境...',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Color(0xff333333), fontSize: setSp(18)),
                          ),
                        ],
                      ),
                    ),
                    // 检测环境 (结果)
                    Offstage(
                      offstage: !isDetectionEnvironment,
                      child: Column(
                        children: [
                          SizedBox(
                            height: setWidth(70),
                          ),
                          Image.asset(
                            'assets/images/security_image.png',
                            height: setWidth(80),
                            width: setWidth(80),
                            fit: BoxFit.fill,
                          ),
                          SizedBox(
                            height: setWidth(30),
                          ),
                          Text(
                            '您的账户当前处于安全环境，可直接\n输入更换的新手机号',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                color: Color(0xff333333), fontSize: setSp(18)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              //修改手机号
              Container(
                color: Colors.white,
                child: ListView(
                  children: [
                    // 获取验证码
                    Offstage(
                      offstage: acquireOrFillIn,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: setWidth(45),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: setWidth(30)),
                            child: Text(
                              '请输入您需要绑定的新手机号',
                              style: TextStyle(
                                  color: Color(0xff333333),
                                  fontSize: setSp(18)),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.symmetric(
                              horizontal: setWidth(30),
                              vertical: setWidth(45),
                            ),
                            decoration: BoxDecoration(
                              border: Border(
                                bottom: BorderSide(
                                  color: Color(0xfff0f0f0),
                                  width: setWidth(0.5),
                                ),
                              ),
                            ),
                            height: setWidth(60),
                            child: Row(
                              children: [
                                Text(
                                  '+86',
                                  style: TextStyle(
                                    color: Color(0xff333333),
                                    fontSize: setSp(12),
                                  ),
                                ),
                                Icon(
                                  Icons.arrow_forward_ios,
                                  size: setWidth(10),
                                  color: Color(0xff999999),
                                ),
                                Expanded(
                                  child: TextField(
                                    controller: _phone,
                                    textAlign: TextAlign.left,
                                    style: TextStyle(fontSize: setSp(16)),
                                    maxLines: 1,
                                    textInputAction: TextInputAction.done,
                                    onSubmitted: (str) {},
                                    onChanged: (val){
                                      setState(() {

                                      });
                                    },
                                    decoration: InputDecoration(
                                      hintText: '请输入手机号',
                                      contentPadding: EdgeInsets.only(
                                        left: setWidth(15),
                                        top: setWidth(10),
                                        bottom: setWidth(10),
                                      ),
                                      isDense: true,
                                      border: InputBorder.none,
                                      focusedBorder: InputBorder.none,
                                      enabledBorder: InputBorder.none,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          InkWell(
                            onTap: () async {
                              _countdown();

                            },
                            child: Container(
                              margin: EdgeInsets.symmetric(
                                horizontal: setWidth(30),
                              ),
                              decoration: BoxDecoration(
                                color: YTTheme.theme.withOpacity(_phone.text.trim().length < 10 ? 0.4 : 1),
                                borderRadius:
                                    BorderRadius.circular(setWidth(3)),
                              ),
                              alignment: Alignment.center,
                              height: setWidth(44),
                              child: Text(
                                '获取验证码',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: setSp(15),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // 输入验证码
                    Offstage(
                      offstage: !acquireOrFillIn,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            height: setWidth(45),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: setWidth(30)),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                GestureDetector(
                                  onTap:(){
                                   urlPush(context, "yuntu://modify_success");
                                  },
                                  child: Text(
                                    '输入验证码',
                                    style: TextStyle(
                                      color: Color(0xff333333),
                                      fontSize: setSp(18),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: setWidth(10),
                                ),
                                Text(
                                  '验证码已发送至+86 ${_phone.text.trim()}',
                                  style: TextStyle(
                                    color: Color(0xff333333),
                                    fontSize: setSp(12),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(
                            height: setWidth(40),
                          ),
                          SizedBox(
                            height: 44,
                            child: Padding(
                              padding: EdgeInsets.symmetric(
                                  horizontal: setWidth(30)),
                              child: PinInputTextField(
                                controller: _checkCode,
                                pinLength: 6,
                                decoration: UnderlineDecoration(
                                  colorBuilder: PinListenColorBuilder(
                                      Color(0xfff0f0f0), Color(0xfff0f0f0)),
                                  bgColorBuilder: PinListenColorBuilder(
                                      Colors.transparent, Colors.transparent),
                                  hintText: '      ',
                                ),
                                textInputAction: TextInputAction.done,
                                enabled: true,
                                textCapitalization:
                                    TextCapitalization.characters,
                                keyboardType: TextInputType.datetime,
                                onSubmit: (pin) {
                                  debugPrint(
                                      'submit pin:$pin'); // return  按钮点击事件
                                },
                                onChanged: (pin) async {
                                  debugPrint(
                                      'onChanged execute. pin:$pin'); // 输入变化事件!
                                  if (pin.length == 6) {}
                                },
                                enableInteractiveSelection: false,
                              ),
                            ),
                          ),
                          SizedBox(
                            height: setWidth(10),
                          ),
                          Padding(
                            padding: EdgeInsets.only(
                              left: setWidth(30),
                              right: setWidth(30),
                            ),
                            child: InkWell(
                              onTap: () {
                                print('重新获取验证码 点击事件!!!');
                              },
                              child: Container(
                                padding: EdgeInsets.only(
                                  top: setWidth(10),
                                  bottom: setWidth(10),
                                ),
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  _countdownNum == 60?"获取验证码":  "${_countdownNum}s后重新获取",
                                  style: TextStyle(
                                    color: _countdownNum == 60
                                        ? Color(0xff1666f1)
                                        : Color(0xff999999),
                                    fontSize: setSp(12),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ]),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    timer?.cancel();
    _countdownTimer?.cancel();
  }
  //发送验证码 倒计时
  _countdown(){
    if(_phone.text.toString().trim() == ""){
      toast("请输入手机号码");
      return;
    }

    if (_countdownTimer != null) {
      return;
    }
    //显示输入验证码
    setState(() {
      acquireOrFillIn = true;
    });
    //获取验证码
    _getCheckCode();


  }
  _getCheckCode(){
    //     开启倒计时
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          _countdownNum -= 1;
          print(_countdownNum);
        } else {
          _countdownNum = 60;
          _countdownTimer.cancel();
          _countdownTimer = null;
        }
      });
    });

  }
}
